package com.huluobo.a2308douyindemo.demo

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.huluobo.a2308douyindemo.MainActivity
import com.huluobo.a2308douyindemo.R

/**
 * LiveData总结:
 * 1.声明LiveData
 * 2.在对应的位置给LiveData赋值,赋值分为2种形式,postValue子线程赋值,value=主线程赋值
 * 3.在任意位置观察LiveData的数据变化,当产生变化的时候,可以在onChanged方法中观察到具体数据
 * 4.观察数据变化的时候可以简写,直接写大括号,省略onChanged
 */
class CountDownActivity : AppCompatActivity() {
    private lateinit var time: TextView
    private lateinit var countDownViewModel: CountDownViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_count_down)
        time = findViewById(R.id.time)

        countDownViewModel = ViewModelProvider(this)[CountDownViewModel::class.java]
        val countDownManager = CountDownManager(countDownViewModel.time)
        //产生订阅关系
        lifecycle.addObserver(countDownManager)

        //观察倒计时的LiveData
//        countDownManager.timeLiveData.observe(this, object : Observer<Int> {
//            override fun onChanged(value: Int) {
//                if (value == 0) {
//                    val intent = Intent(this@CountDownActivity, MainActivity::class.java)
//                    startActivity(intent)
//                }
//                time.text = "倒计时${value}秒"
//            }
//        })

        //观察LiveData简写
        countDownManager.timeLiveData.observe(this) { value ->
            if (value == 0) {
                val intent = Intent(this@CountDownActivity, MainActivity::class.java)
                startActivity(intent)
            }
            time.text = "倒计时${value}秒"
            //由于倒计时传递回来的值是个int,但是倒计时的赋值需要是个long,
            countDownViewModel.time = value * 1000L
        }

        findViewById<Button>(R.id.toMain).setOnClickListener {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
        }
    }
}